package cn.jw.starter.web.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 全局异常捕获
 *
 * @author wgslucky
 * @since 2024/4/30 19:19
 **/
@ControllerAdvice
public class GlobalExceptionHandler {

    private static Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    public GlobalExceptionHandler() {
        logger.info("初始化全局异常捕获成功");
    }

    @ExceptionHandler(Throwable.class)
    @ResponseBody
    public Object errorHandler(Throwable ex) {
        logger.error("服务器异常", ex);
        if (ex instanceof JwServiceException) {
            JwServiceException jx = (JwServiceException)ex;
            return JwCommonResult.error(jx.getErrorBase(), jx.getMessage());
        } else {
            return JwCommonResult.error(500, "服务器异常:" + ex.getMessage());
        }
    }
}
